//
//  CLVCNovelContent.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/4/29.
//

#import "CLVCNovelContent.h"
#import "CLCoreText.h"
#import "CLReadView.h"
#import "CLReadConfigure.h"
#import "CLExtentionsManager.h"
#import "CLWebDataView.h"
@interface CLVCNovelContent ()
@property (nonatomic, strong) CLReadView *textView;
@property (nonatomic, strong) NSArray <NSValue *>*rects;
@property (nonatomic, assign) NSUInteger page;
@property (nonatomic, strong) UITapGestureRecognizer *tap;
@end

@implementation CLVCNovelContent

- (void)viewDidLoad {
    [super viewDidLoad];
    self.backgroundView.backgroundColor = [CLReadConfigure sharedInstance].bgColor;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapContent:)];
    self.tap = tap;
    [self.view addGestureRecognizer:tap];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self request];
}

- (void)request {
    WEAK_SELF;
    BOOL (^_updateContentBlock)(void) = ^{
        if (!NULLString(weakSelf.chapter.content)) {
            [SVProgressHUD dismiss];
            NSAttributedString *content = [weakSelf getAttributedWithString:weakSelf.chapter.content];
            CGRect rect = [weakSelf textRect];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                NSArray <NSValue *>*rects = [CLCoreText getPageingRanges:content rect:rect];
                weakSelf.rects = rects;
                NSString *text = [weakSelf.chapter.content substringWithRange:[rects.firstObject rangeValue]];
                JSLog(@"分页：%ld,%@",rects.count,[text cl_substringFromIndex:text.length - 5]);
                dispatch_main_safe_async(^{
                    CLReadPageModel *pageModel = [[CLReadPageModel alloc]init];
                    pageModel.contentSize = rect.size;
                    pageModel.content = [weakSelf getAttributedWithString:text];
                    weakSelf.textView.pageModel = pageModel;
                });
            });
            JSLog(@"[native] %@获取内容成功%ld",weakSelf.chapter.chapterid,weakSelf.chapter.content.length);
            [weakSelf.chapter removeObserverAndBlock];
            return NO;
        }
        return YES;
    };
    
    if (_updateContentBlock()) {
        [SVProgressHUD showLoading];
        JSLog(@"[native]打开并监听章节:%@,%ld",_chapter.chapterid,_chapter.content.length);
        [_chapter requestWithCompleteBlock:^{
            CLSafeExecuteBlock(_updateContentBlock);
        }];
    }
}

- (void)setChapter:(CLReadChapterModel *)chapter {
    _chapter = chapter;
    JSLog(@"[native] 阅读页<%p>%@",chapter,chapter.chapterid);
    self.title = _chapter.name;
}

- (void)tapContent:(UITapGestureRecognizer *)tap {
    CGPoint point = [tap locationInView:self.view];
    NSString *text = @"";
    if (point.y > self.view.height / 2) {
        NSUInteger next = self.page + 1;
        if (next < self.rects.count) {
            text = [self.chapter.content substringWithRange:[[self.rects objectAtIndex:next] rangeValue]];
            CLReadPageModel *pageModel = [[CLReadPageModel alloc]init];
            pageModel.contentSize = [self textRect].size;
            pageModel.content = [self getAttributedWithString:text];
            self.textView.pageModel = pageModel;
            self.page = next;
        } else {
            /// 下一章
            [CLExtentionsManager.sharedInstance webView:CLWebDataView.shared.webView nextChapter:YES];
        }
    } else {
        NSUInteger next = self.page - 1;
        text = [self.chapter.content substringWithRange:[[self.rects objectAtIndex:next] rangeValue]];
        if (self.page > 0 && next >= 0) {
            CLReadPageModel *pageModel = [[CLReadPageModel alloc]init];
            pageModel.contentSize = [self textRect].size;
            pageModel.content = [self getAttributedWithString:text];
            self.textView.pageModel = pageModel;
            self.page = next;
        } else {
            [CLExtentionsManager.sharedInstance webView:CLWebDataView.shared.webView nextChapter:NO];
        }
    }
    JSLog(@"page：%@",[text cl_substringFromIndex:text.length - 5]);
}

- (CLReadView *)textView {
    if (!_textView) {
        _textView = [[CLReadView alloc]init];
        [self.contentView addSubview:_textView];
        [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.contentView);
        }];
    }
    return _textView;
}

- (NSAttributedString *)getAttributedWithString:(NSString *)string  {
    NSMutableAttributedString *contentString = [[NSMutableAttributedString alloc]initWithString:string attributes:[CLReadConfigure.sharedInstance attributesByIsTitle:NO isPageing:NO]];
    return contentString;
}

- (void)dealloc {
    [self.chapter removeObserverAndBlock];
    CLDealloc;
}

- (BOOL)isHiddenNaviBar {
    return YES;
}

- (CGRect)textRect {
    return SCREENBOUNDS;
}
@end
